package com.itboye.jigongbao.widget;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

import com.itboye.jigongbao.R;
import com.itboye.jigongbao.app.MyApplication;
import com.itboye.jigongbao.bean.MonthAccountBean;
import com.itboye.jigongbao.utils.ByTimeUtils;
import com.itboye.jigongbao.utils.Const;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import static com.itboye.jigongbao.utils.ByTimeUtils.timeFormat;
import static com.itboye.jigongbao.utils.ByTimeUtils.timeParse;

public class MyCalendarView extends View implements View.OnTouchListener {
    private final static String TAG = "anCalendar";
    private Date selectedStartDate;
    private Date selectedEndDate;
    private Date fristDate, secondDate;
    private Date curDate; // 当前日历显示的月
    private Date today; // 今天的日期文字显示红色
    private Date downDate; // 手指按下状态时临时日期
    private Date showFirstDate, showLastDate; // 日历显示的第一个日期和最后一个日期
    private int downIndex; // 按下的格子索引
    private int selectIndex = -1;
    private Calendar calendar;
    private Surface surface;
    private int[] date = new int[42]; // 日历显示数字
    private int curStartIndex, curEndIndex; // 当前显示的日历起始的索引

    private ArrayList<MonthAccountBean> accountBeanArrayList = new ArrayList<>();//用户月账本信息
    // private boolean completed = false; // 为false表示只选择了开始日期，true表示结束日期也选择了
    // 给控件设置监听事件
    private OnItemClickListener onItemClickListener;

    private OnItemClickEndListener onItemClickEndListener;

    private boolean isWorker;//身份标识

    int startposition = -1, endposition = -1;
    private int mOffsetHeight;

    public MyCalendarView(Context context) {
        super(context);
        init();
    }

    public MyCalendarView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public void setUserAccountData(ArrayList<MonthAccountBean> accountBeanArrayList, boolean isWorker) {
        this.accountBeanArrayList = accountBeanArrayList;
        this.isWorker = isWorker;
        invalidate();
    }

    private void init() {

        curDate = selectedStartDate = selectedEndDate = today = new Date();
        calendar = Calendar.getInstance();
        calendar.setTime(curDate);
        surface = new Surface();
        surface.density = getResources().getDisplayMetrics().density;
        setBackgroundColor(surface.bgColor);
        setOnTouchListener(this);
    }

    public String setDate(String time) {
        long timeParse = ByTimeUtils.timeParse("yyyyMM", time);
        curDate = new Date(timeParse);
        String date = getYearAndmonth();
        invalidate();
        return date;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        surface.width = getResources().getDisplayMetrics().widthPixels;
        surface.height = (int) (getResources().getDisplayMetrics().heightPixels * 0.55f);
        // if (View.MeasureSpec.getMode(widthMeasureSpec) ==
        // View.MeasureSpec.EXACTLY) {
        // surface.width = View.MeasureSpec.getSize(widthMeasureSpec);
        // }
        // if (View.MeasureSpec.getMode(heightMeasureSpec) ==
        // View.MeasureSpec.EXACTLY) {
        // surface.height = View.MeasureSpec.getSize(heightMeasureSpec);
        // }
        widthMeasureSpec = MeasureSpec.makeMeasureSpec(surface.width, MeasureSpec.EXACTLY);
        heightMeasureSpec = MeasureSpec.makeMeasureSpec(surface.height, MeasureSpec.EXACTLY);
        mOffsetHeight = heightMeasureSpec;
        setMeasuredDimension(widthMeasureSpec, heightMeasureSpec);
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        Log.d(TAG, "[onLayout] changed:" + (changed ? "new size" : "not change") + " left:" + left + " top:" + top
                + " right:" + right + " bottom:" + bottom);
        if (changed) {
            surface.init();
        }
        super.onLayout(changed, left, top, right, bottom);
    }

    float bottomY = 0;

    Canvas mCanvas;

    @Override
    protected void onDraw(Canvas canvas) {
        mCanvas = canvas;
        Log.d(TAG, "onDraw");
        // 画框
        // canvas.drawPath(surface.boxPath, surface.borderPaint);
        // 年月
        // String monthText = getYearAndmonth();
        // float textWidth = surface.monthPaint.measureText(monthText);
        // canvas.drawText(monthText, (surface.width - textWidth) / 2f,
        // surface.monthHeight * 3 / 4f, surface.monthPaint);
        // 上一月/下一月
        // canvas.drawPath(surface.preMonthBtnPath,
        // surface.monthChangeBtnPaint);
        // canvas.drawPath(surface.nextMonthBtnPath,
        // surface.monthChangeBtnPaint);
        // 星期
        float weekTextY = surface.monthHeight + surface.weekHeight * 3 / 4f;
        // 星期背景
//		 surface.cellBgPaint.setColor(surface.textColor);
        // canvas.drawRect(surface.weekHeight, surface.width,
        // surface.weekHeight, surface.width, surface.cellBgPaint);
        drawWeekBg(canvas);//画星期栏目背景
        for (int i = 0; i < surface.weekText.length; i++) {
            float weekTextX = i * surface.cellWidth
                    + (surface.cellWidth - surface.weekPaint.measureText(surface.weekText[i])) / 2f;
            if (i == 0 || i == surface.weekText.length - 1) {
                surface.weekPaint.setColor(surface.weekendColor);
            } else {
                surface.weekPaint.setColor(surface.weekNormalColor);
            }
            canvas.drawText(surface.weekText[i], weekTextX, weekTextY, surface.weekPaint);
        }

        // 计算日期
        calculateDate();
        // 按下状态，选择状态背景色

        // write date number
        // today index
        int todayIndex = -1;
        calendar.setTime(curDate);
        String curYearAndMonth = calendar.get(Calendar.YEAR) + "" + calendar.get(Calendar.MONTH);
        calendar.setTime(today);
        String todayYearAndMonth = calendar.get(Calendar.YEAR) + "" + calendar.get(Calendar.MONTH);
        if (curYearAndMonth.equals(todayYearAndMonth)) {
            int todayNumber = calendar.get(Calendar.DAY_OF_MONTH);
            todayIndex = curStartIndex + todayNumber - 1;
        }

        //画按下的日期效果
        if (selectIndex != -1) {
            drawCurrentDateCellBg(canvas, selectIndex, surface.startTimePaint);
        }

        float[] cell = new float[2];
        for (int i = 0; i < 35; i++) {
            int color = surface.textColor;
            boolean isLast = isLastMonth(i);
            boolean isNext = isNextMonth(i);
            if (isLast) {
                color = surface.borderColor;
                //如果是上个月的日期，当前月--去比较
//                Log.v(Const.Companion.getTAG_DEBUG(), "last month date: " + date[i]);
            } else if (isNext) {
                //如果是下个月的日期，当前月++去比较
                color = surface.borderColor;
//                Log.v(Const.Companion.getTAG_DEBUG(), "next month date: " + date[i]);
            }
            if (todayIndex != -1 && i == todayIndex) {
                color = surface.todayNumberColor;
                drawCurrentDateCellBg(canvas, i, surface.startTimePaint);
//                drawCellBg(canvas, downIndex, "", surface.startTimePaint);
//                drawDownOrSelectedBg(canvas, surface.startTimePaint);
            }
            cell = drawCellText(canvas, i, date[i] + "", color);
            drawBottomCircle(canvas, i, date[i] + "", isLast, isNext);
        }
        bottomY = cell[1];
        drawButtomValue(canvas, cell);
//		if (startposition == -1 && endposition == -1) {
//
//			if (!isPreferences.getSp().getString("start_time", "").equals("")
//					&& !isPreferences.getSp().getString("end_time", "").equals("")) {
//				
////				drawDownOrSelectedBg(canvas, surface.startTimePaint);
//				
//				drawCellBg(canvas, isPreferences.getSp().getInt("start_index", 0), surface.startTimePaint);
//				drawCellBg(canvas, isPreferences.getSp().getInt("end_index", 0), surface.endTimePaint);
//			}
//		}

        if (onItemClickListener != null) {
            if (startposition != -1)
                drawCellBg(canvas, downIndex, "", surface.startTimePaint);
        }

        if (onItemClickEndListener != null) {
            if (startposition != -1 && endposition != -1) {
                drawCellBg(canvas, start_index, "", surface.startTimePaint);
                drawCellBg(canvas, downIndex, "", surface.endTimePaint);
            }
        }


        super.onDraw(canvas);
    }

    private void drawButtomValue(Canvas canvas, float[] cell) {
//        Paint paint = new Paint();
//        paint.setTextSize(26);
//        paint.setAntiAlias(true);
        surface.bottomValuePaint.setColor(getResources().getColor(R.color.gray_B3));
        canvas.drawLine(0, cell[1] + surface.cellWidth / 2 - 10, surface.width, cell[1] + surface.cellWidth / 2 - 10, surface.bottomValuePaint);
        String text = "1d=1个工 1h=1小时";
        surface.bottomValuePaint.setColor(getResources().getColor(R.color.main_blue));
        canvas.drawText(text, cell[0] + surface.cellWidth / 2, cell[1] + surface.cellHeight, surface.bottomValuePaint);
        String textTotal = "■上班 ■加班";
        String text1 = "■";
        float x1 = surface.width - surface.bottomValuePaint.measureText(textTotal) - surface.cellWidth / 2;
        canvas.drawText((text1), x1, cell[1] + surface.cellHeight, surface.bottomValuePaint);
        String text2 = "上班";
        surface.bottomValuePaint.setColor(getResources().getColor(R.color.black));
        float x2 = x1 + surface.bottomValuePaint.measureText(text2) / 2;
        canvas.drawText((text2), x1 + surface.bottomValuePaint.measureText(text2) / 2, cell[1] + surface.cellHeight, surface.bottomValuePaint);
        String text3 = "■";
        surface.bottomValuePaint.setColor(getResources().getColor(R.color.gallery_red));
        float x3 = x2 + surface.bottomValuePaint.measureText(text1 + text2);
        canvas.drawText((text3), x3, cell[1] + surface.cellHeight, surface.bottomValuePaint);
        String text4 = "加班";
        canvas.drawText((text4), x2 + surface.bottomValuePaint.measureText(text1 + text2 + text3), cell[1] + surface.cellHeight, surface.bottomValuePaint);
//        canvas.drawText(Html.fromHtml(textTotal), 0, textTotal.length()-1, surface.width - paint.measureText(text) - surface.cellWidth / 2, cell[1] + surface.cellHeight, paint);
//        canvas.drawText((text), surface.width - paint.measureText(text) - surface.cellWidth / 2, cell[1] + surface.cellHeight, paint);
    }

    private void drawBottomCircle(Canvas canvas, int index, String text, boolean isLast, boolean isNext) {
        int x = getXByIndex(index);
        int y = getYByIndex(index);
        // surface.cellBgPaint.setColor(color);
        float left = surface.cellWidth * (x - 1) + surface.borderWidth;
        float top = surface.monthHeight + surface.weekHeight + (y - 1) * surface.cellHeight + surface.borderWidth;
        //
//		canvas.drawCircle(left + surface.cellWidth / 2f, top + surface.cellHeight * 0.55f, surface.cellWidth * 0.45f,
//				mPaint);
//        if (isJiaBan()) {
//            //如果是加班
//            Log.v(Const.Companion.getTAG_DEBUG(), date + "today is jiaban day");
//        } else {
//
//        }
        float circleX = left + surface.cellWidth / 2f;
        float circleY = top + surface.cellHeight * 0.55f + surface.cellWidth * 0.35f;
        int type[] = isShangBan(text, isLast, isNext);
        if (type[0] == 0) {
            //正常上班
            canvas.drawCircle(circleX, circleY, 5, surface.shangBanPaint);
        } else if (type[0] == 1) {
            //有加班
            canvas.drawCircle(circleX, circleY, 5, surface.jiaBanPaint);
            if (isWorker) {
                //画加班时长
                Paint paintHours = new Paint();
                paintHours.setColor(MyApplication.Companion.getInstance().getResources().getColor(R.color.gallery_red));
                paintHours.setTextSize(surface.jiaBanPaint.getTextSize() * 1.5f);
                paintHours.setAntiAlias(true);
                String hoursValue = type[1] + "h";
                Rect rect = new Rect();
                paintHours.getTextBounds(hoursValue, 0, hoursValue.length(), rect);
                int width = rect.width();//文字宽
                int height = rect.height();//文字高
                canvas.drawText(hoursValue, circleX + 10, circleY + height / 2, paintHours);
            } else {

            }

        } else {
//            canvas.drawCircle(left + surface.cellWidth / 2f, top + surface.cellHeight * 0.55f + surface.cellWidth * 0.35f, 5, surface.datePaint);
        }
    }

    private boolean isJiaBan() {
        return false;
    }

    /**
     * @param date   上班日期
     * @param isLast 是否是上一个月的日期
     * @param isNext 是否是下一个月的日期
     * @return 数组第一位[-1无上班加班记录 0正常上班，1加班] 数组第二位[加班时长]
     */
    private int[] isShangBan(String date, boolean isLast, boolean isNext) {
        int type[] = new int[]{-1, -1};
        for (int i = 0; i < accountBeanArrayList.size(); i++) {
            MonthAccountBean accountBean = accountBeanArrayList.get(i);
            String sbDate = accountBean.getDay();//上班的时间 如：20180101
            String currentYM = timeFormat("yyyyMM", curDate.getTime());
            if (isLast) {
                currentYM = (Integer.parseInt(currentYM) - 1) + "";
            }
            if (isNext) {
                currentYM = (Integer.parseInt(currentYM) + 1) + "";
            }
            String currentYMD = timeFormat("yyyyMMdd", timeParse("yyyyMMdd", currentYM + date));
            Log.v(Const.Companion.getTAG_DEBUG(), date + "::data--->" + currentYMD);
            if (sbDate.equals(currentYMD)) {
                //overtime<=0表示未加班
                if (isWorker) {
                    if (accountBean.getOvertime() <= 0) {
                        type[0] = 0;
                    } else {
                        type[0] = 1;
                    }
                    type[1] = accountBean.getOvertime();
                } else {
                    if (accountBean.getOver_cnt() <= 0) {
                        type[0] = 0;
                    } else {
                        type[0] = 1;
                    }
                    type[1] = accountBean.getOver_cnt();
                }
                break;
            }
        }
        return type;
    }

    private void drawWeekBg(Canvas canvas) {
        Paint paint = new Paint();
        paint.setColor(MyApplication.Companion.getInstance().getResources().getColor(R.color.main_blue));
        canvas.drawRect(0f, 0f, surface.width, surface.weekHeight, paint);
    }

    private void calculateDate() {
        calendar.setTime(curDate);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        int dayInWeek = calendar.get(Calendar.DAY_OF_WEEK);
        Log.d(Const.Companion.getTAG_DEBUG(), "day in week:" + dayInWeek);
        int monthStart = dayInWeek;
        if (monthStart == 1) {
            monthStart = 8;
        }
        monthStart -= 1; // 以日为开头-1，以星期一为开头-2
        curStartIndex = monthStart;
        date[monthStart] = 1;
        // last month
        if (monthStart > 0) {
            calendar.set(Calendar.DAY_OF_MONTH, 0);
            int dayInmonth = calendar.get(Calendar.DAY_OF_MONTH);
            for (int i = monthStart - 1; i >= 0; i--) {
                date[i] = dayInmonth;
                dayInmonth--;
            }
            calendar.set(Calendar.DAY_OF_MONTH, date[0]);
        }
        showFirstDate = calendar.getTime();
        // this month
        calendar.setTime(curDate);
        calendar.add(Calendar.MONTH, 1);
        calendar.set(Calendar.DAY_OF_MONTH, 0);
        // Log.d(TAG, "m:" + calendar.get(Calendar.MONTH) + " d:" +
        // calendar.get(Calendar.DAY_OF_MONTH));
        int monthDay = calendar.get(Calendar.DAY_OF_MONTH);
        for (int i = 1; i < monthDay; i++) {
            date[monthStart + i] = i + 1;
        }
        curEndIndex = monthStart + monthDay;
        // next month
        for (int i = monthStart + monthDay; i < 42; i++) {
            date[i] = i - (monthStart + monthDay) + 1;
        }
        if (curEndIndex < 42) {
            // 显示了下一月的
            calendar.add(Calendar.DAY_OF_MONTH, 1);
        }
        calendar.set(Calendar.DAY_OF_MONTH, date[41]);
        showLastDate = calendar.getTime();
    }

    /**
     * @param canvas
     * @param index
     * @param text
     */
    private float[] drawCellText(Canvas canvas, int index, String text, int color) {
        float[] point = new float[2];
        int x = getXByIndex(index);
        int y = getYByIndex(index);
        surface.datePaint.setColor(color);
        float cellY = surface.monthHeight + surface.weekHeight + (y - 1) * surface.cellHeight
                + surface.cellHeight * 3 / 4f;
        float cellX = (surface.cellWidth * (x - 1)) + (surface.cellWidth - surface.datePaint.measureText(text)) / 2f;
        canvas.drawText(text, cellX, cellY, surface.datePaint);
        if (index == 29) {
            point[0] = cellX;
        }
        point[1] = cellY;
        return point;
//        drawCellBg(canvas, index, text, surface.datePaint);
    }

    private void drawCurrentDateCellBg(Canvas canvas, int index, Paint mPaint) {
        int x = getXByIndex(index);
        int y = getYByIndex(index);
        // surface.cellBgPaint.setColor(color);
        float left = surface.cellWidth * (x - 1) + surface.borderWidth;
        float top = surface.monthHeight + surface.weekHeight + (y - 1) * surface.cellHeight + surface.borderWidth;
        //
        canvas.drawCircle(left + surface.cellWidth / 2f, top + surface.cellHeight * 0.65f, surface.cellWidth * 0.45f,
                mPaint);
    }

    /**
     * @param canvas
     * @param index
     * @param mPaint
     */
    private void drawCellBg(Canvas canvas, int index, String text, Paint mPaint) {
        int x = getXByIndex(index);
        int y = getYByIndex(index);
        // surface.cellBgPaint.setColor(color);
        float left = surface.cellWidth * (x - 1) + surface.borderWidth;
        float top = surface.monthHeight + surface.weekHeight + (y - 1) * surface.cellHeight + surface.borderWidth;
        //
//		canvas.drawCircle(left + surface.cellWidth / 2f, top + surface.cellHeight * 0.55f, surface.cellWidth * 0.45f,
//				mPaint);
//        if (isJiaBan()) {
//            //如果是加班
//            Log.v(Const.Companion.getTAG_DEBUG(), date + "today is jiaban day");
//        } else {
//
//        }
//        if (isShangBan(text)) {
        //如果是上班
        canvas.drawCircle(left + surface.cellWidth / 2f, top + surface.cellHeight * 0.55f + surface.cellWidth * 0.35f, 5, surface.shangBanPaint);
//        } else {
//            canvas.drawCircle(left + surface.cellWidth / 2f, top + surface.cellHeight * 0.55f + surface.cellWidth * 0.35f, 5, surface.datePaint);
//        }
//        canvas.drawCircle(left + surface.cellWidth / 2f, top + surface.cellHeight * 0.55f + surface.cellWidth * 0.35f, 5, surface.datePaint);
        // canvas.drawRect(left, top, left + surface.cellWidth
        // - surface.borderWidth, top + surface.cellHeight
        // - surface.borderWidth, surface.cellBgPaint);
    }

    private void drawDownOrSelectedBg(Canvas canvas, Paint mPaint) {
        // down and not up
        if (downDate != null) {
            drawCellBg(canvas, downIndex, "", mPaint);

        }
        // selected bg color
        if (!selectedEndDate.before(showFirstDate) && !selectedStartDate.after(showLastDate)) {
            int[] section = new int[]{-1, -1};
            calendar.setTime(curDate);
            calendar.add(Calendar.MONTH, -1);
            findSelectedIndex(0, curStartIndex, calendar, section);
            if (section[1] == -1) {
                calendar.setTime(curDate);
                findSelectedIndex(curStartIndex, curEndIndex, calendar, section);
            }
            if (section[1] == -1) {
                calendar.setTime(curDate);
                calendar.add(Calendar.MONTH, 1);
                findSelectedIndex(curEndIndex, 42, calendar, section);
            }
            if (section[0] == -1) {
                section[0] = 0;
            }
            if (section[1] == -1) {
                section[1] = 41;
            }
            for (int i = section[0]; i <= section[1]; i++) {
                drawCellBg(canvas, i, "", mPaint);
            }
        }
    }

    private void findSelectedIndex(int startIndex, int endIndex, Calendar calendar, int[] section) {
        for (int i = startIndex; i < endIndex; i++) {
            calendar.set(Calendar.DAY_OF_MONTH, date[i]);
            Date temp = calendar.getTime();
            // Log.d(TAG, "temp:" + temp.toLocaleString());
            if (temp.compareTo(selectedStartDate) == 0) {
                section[0] = i;
            }
            if (temp.compareTo(selectedEndDate) == 0) {
                section[1] = i;
                return;
            }
        }
    }

    public Date getSelectedStartDate() {
        return selectedStartDate;
    }

    public Date getSelectedEndDate() {
        return selectedEndDate;
    }

    private boolean isLastMonth(int i) {
        if (i < curStartIndex) {
            return true;
        }
        return false;
    }

    private boolean isNextMonth(int i) {
        if (i >= curEndIndex) {
            return true;
        }
        return false;
    }

    private int getXByIndex(int i) {
        return i % 7 + 1; // 1 2 3 4 5 6 7
    }

    private int getYByIndex(int i) {
        return i / 7 + 1; // 1 2 3 4 5 6
    }

    // 获得当前应该显示的年月
    public String getYearAndmonth() {
        calendar.setTime(curDate);
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        return year + "年" + surface.monthText[month];
    }

    // 上一月
    public String clickLeftMonth() {
        calendar.setTime(curDate);
        calendar.add(Calendar.MONTH, -1);
        curDate = calendar.getTime();
//		if (surface != null && surface.startTimePaint!=null && surface.endTimePaint!=null) {
//			surface.startTimePaint.setColor(Color.WHITE);
//			surface.startTimePaint.setColor(Color.WHITE);
//		}
        invalidate();
        return getYearAndmonth();
    }

    // 下一月
    public String clickRightMonth() {
        calendar.setTime(curDate);
        calendar.add(Calendar.MONTH, 1);
        curDate = calendar.getTime();
//		if (surface != null) {
//			surface.startTimePaint.setColor(Color.WHITE);
//			surface.startTimePaint.setColor(Color.WHITE);
//		}
        invalidate();
        return getYearAndmonth();
    }

    private void setSelectedDateByCoor(float x, float y) {
        // change month
        // if (y < surface.monthHeight) {
        // // pre month
        // if (x < surface.monthChangeWidth) {
        // calendar.setTime(curDate);
        // calendar.add(Calendar.MONTH, -1);
        // curDate = calendar.getTime();
        // }
        // // next month
        // else if (x > surface.width - surface.monthChangeWidth) {
        // calendar.setTime(curDate);
        // calendar.add(Calendar.MONTH, 1);
        // curDate = calendar.getTime();
        // }
        // }
        // cell click down
        if ((y > surface.monthHeight + surface.weekHeight) && y < bottomY) {
            int m = (int) (Math.floor(x / surface.cellWidth) + 1);
            int n = (int) (Math
                    .floor((y - (surface.monthHeight + surface.weekHeight)) / Float.valueOf(surface.cellHeight)) + 1);
            downIndex = (n - 1) * 7 + m - 1;
            Log.d(TAG, "downIndex:" + downIndex);
            calendar.setTime(curDate);
            if (isLastMonth(downIndex)) {
                calendar.add(Calendar.MONTH, -1);
            } else if (isNextMonth(downIndex)) {
                calendar.add(Calendar.MONTH, 1);
            }
            if (downIndex >= date.length) {
//                calendar.set(Calendar.DAY_OF_MONTH, date[downIndex]);
            } else {
                calendar.set(Calendar.DAY_OF_MONTH, date[downIndex]);
            }
            downDate = calendar.getTime();
        }
        Log.v(Const.Companion.getTAG_DEBUG(), "down date" + downDate);
        invalidate();
    }

    private void setSelectBg(float x, float y) {
        if ((y > surface.monthHeight + surface.weekHeight) && y < bottomY) {
            int m = (int) (Math.floor(x / surface.cellWidth) + 1);
            int n = (int) (Math
                    .floor((y - (surface.monthHeight + surface.weekHeight)) / Float.valueOf(surface.cellHeight)) + 1);
            selectIndex = (n - 1) * 7 + m - 1;
            invalidate();
//            drawCurrentDateCellBg(mCanvas, selectIndex, surface.startTimePaint);
        }
    }

    int start_index = 0, end_index = 0;

    boolean mBottomFlag;

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN)
            //假设是新的按下事件。则对mBottomFlag又一次初始化
            mBottomFlag = false;
        //假设已经不要这次事件。则传出取消的信号，这里的作用不大
        if (mBottomFlag)
            event.setAction(MotionEvent.ACTION_CANCEL);
        return super.dispatchTouchEvent(event);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        boolean result = super.onTouchEvent(event);
        //假设是须要拦截，则再拦截，这种方法会在onScrollChanged方法之后再调用一次
        if (!mBottomFlag)
            getParent().requestDisallowInterceptTouchEvent(true);
        return result;
    }

    @Override
    protected void onScrollChanged(int horiz, int vert, int oldHoriz, int oldVert) {
        super.onScrollChanged(horiz, vert, oldHoriz, oldVert);
        if (vert == mOffsetHeight || vert == 0) {
            //这里触发父布局或祖父布局的滑动事件
            getParent().requestDisallowInterceptTouchEvent(false);
            mBottomFlag = true;
        }
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                setSelectBg(event.getX(), event.getY());
//                setSelectedDateByCoor(event.getX(), event.getY());
                break;
            case MotionEvent.ACTION_MOVE:
                selectIndex = -1;
                invalidate();
//                setSelectBg(event.getX(), event.getY());
                break;
            case MotionEvent.ACTION_UP:
                selectIndex = -1;
                setSelectedDateByCoor(event.getX(), event.getY());
                if (downDate != null) {
//                     if (!completed) {
//                    if (downDate.before(selectedStartDate)) {
//                        selectedEndDate = selectedStartDate;
//                        selectedStartDate = downDate;
//                    } else {
//                        selectedEndDate = downDate;
//                    }
//                     completed = true;
//                } else {
                    selectedStartDate = selectedEndDate = downDate;
//                     completed = false;
//                }

//                selectedStartDate = selectedEndDate = downDate;

                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");

//				String start_time = isPreferences.getSp().getString("start_time", "");
//				String end_time = isPreferences.getSp().getString("end_time", "");

//				// 全部为空 点中时为 开始时间
//				if (start_time.equals("") && end_time.equals("")) {
//					isPreferences.updateSp("start_time", sdf.format(selectedStartDate));
//					isPreferences.updateSp("start_date", selectedStartDate);
//					isPreferences.updateSp("start_index", downIndex);
//					start_index = downIndex;
//
//					startposition = 1;
//					// 响应监听事件
//					onItemClickListener.OnItemClick(selectedStartDate);
//
//				} else if (!start_time.equals("") && end_time.equals("")) {// 开始时间已选择，结束时间未选择时
//					// 判断时间在开始时间之前还是之后 ，如果是当前时间之前并且在当天之后就为开始时间，如果在开始时间之后就为结束时间
//					long start_date = Date.parse(isPreferences.getSp().getString("start_date", ""));
//					long select_date = selectedStartDate.getTime();
//
//					Log.i("TAG", "start_date = " + start_date + " , select_date == " + select_date);
//
//					Toast.makeText(getContext(), "start_date = " + start_date + " , select_date == " + select_date,
//							Toast.LENGTH_SHORT).show();
//
//					if (start_date < select_date) {// 选择时间大于开始时间 这个为结束时间
//						isPreferences.updateSp("end_time", sdf.format(selectedStartDate));
//						isPreferences.updateSp("end_index", downIndex);
//						end_index = downIndex;
//						endposition = 1;
//						onItemClickEndListener.onItemEndClick(selectedStartDate);
//					} else if (start_date == select_date) {
//
//					} else {
//						isPreferences.updateSp("start_time", sdf.format(selectedStartDate));
//						isPreferences.updateSp("start_date", selectedStartDate);
//						isPreferences.updateSp("start_index", downIndex);
//						start_index = downIndex;
//
//						startposition = 1;
//						// 响应监听事件
                    onItemClickListener.OnItemClick(selectedStartDate);
//					}
//
//				} else if (!start_time.equals("") && !end_time.equals("")) {// 开始结束时间都选择，重新选择（算成开始时间）
//					isPreferences.updateSp("start_time", sdf.format(selectedStartDate));
//					isPreferences.updateSp("start_date", selectedStartDate);
//					isPreferences.updateSp("end_time", "");
//					isPreferences.updateSp("start_index", downIndex);
//					start_index = downIndex;
//					startposition = 1;
//					// 响应监听事件
//					onItemClickListener.OnItemClick(selectedStartDate);
//				}

                    // Log.d(TAG, "downdate:" + downDate.toLocaleString());
                    // Log.d(TAG, "start:" + selectedStartDate.toLocaleString());
                    // Log.d(TAG, "end:" + selectedEndDate.toLocaleString());
                    downDate = null;

                    invalidate();
                }
                break;
        }
        return true;
    }

    // 给控件设置监听事件
    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }

    // 监听接口
    public interface OnItemClickListener {
        void OnItemClick(Date date);
    }

    public interface OnItemClickEndListener {
        void onItemEndClick(Date date);
    }

    // 给控件设置监听事件
    public void setOnItemClickEndListener(OnItemClickEndListener onItemClickEndListener) {
        this.onItemClickEndListener = onItemClickEndListener;
    }

    /**
     * 1. 布局尺寸 2. 文字颜色，大小 3. 当前日期的颜色，选择的日期颜色
     */
    private class Surface {
        public float density;
        public int width; // 整个控件的宽度
        public int height; // 整个控件的高度
        public float monthHeight; // 显示月的高度
        // public float monthChangeWidth; // 上一月、下一月按钮宽度
        public float weekHeight; // 显示星期的高度
        public float cellWidth; // 日期方框宽度
        public float cellHeight; // 日期方框高度
        public float borderWidth;
        public int bgColor = Color.parseColor("#FFFFFF");
        private int textColor = Color.parseColor("#555555");
        private int weekNormalColor = Color.parseColor("#499BCB");
        private int weekendColor = Color.parseColor("#FFFFFF");
        // private int textColorUnimportant = Color.parseColor("#666666");
        private int btnColor = Color.parseColor("#666666");
        private int borderColor = Color.parseColor("#CCCCCC");
        public int todayNumberColor = Color.parseColor("#FE4081"); // 当天颜色
        public int cellDownColor = Color.parseColor("#99CCFF");
        public int cellSelectedColor = Color.parseColor("#99CCFF");
        public Paint borderPaint;
        public Paint monthPaint;
        public Paint weekPaint;
        public Paint datePaint;
        public Paint monthChangeBtnPaint;
        public Paint cellBgPaint;
        public Paint startTimePaint;
        public Paint endTimePaint;
        public Paint shangBanPaint;
        public Paint jiaBanPaint;
        public Paint bottomValuePaint;
        public Path boxPath; // 边框路径
        // public Path preMonthBtnPath; // 上一月按钮三角形
        // public Path nextMonthBtnPath; // 下一月按钮三角形
        public String[] weekText = {"日", "一", "二", "三", "四", "五", "六"};
        public String[] monthText = {"1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"};

        public void init() {
            float temp = height / 7f;
            monthHeight = 0;// (float) ((temp + temp * 0.3f) * 0.6);
            // monthChangeWidth = monthHeight * 1.5f;
            weekHeight = (float) ((temp + temp * 0.3f) * 0.5);
            cellHeight = (height - monthHeight - weekHeight) / 7f;
            cellWidth = width / 7f;
            borderPaint = new Paint();
            borderPaint.setColor(borderColor);
            borderPaint.setStyle(Paint.Style.STROKE);
            borderWidth = (float) (0.5 * density);
            // Log.d(TAG, "borderwidth:" + borderWidth);
            borderWidth = borderWidth < 1 ? 1 : borderWidth;
            borderPaint.setStrokeWidth(borderWidth);


            monthPaint = new Paint();
            monthPaint.setColor(textColor);
            monthPaint.setAntiAlias(true);
            float textSize = cellHeight * 0.4f;
            Log.d(TAG, "text size:" + textSize);
            monthPaint.setTextSize(textSize);
            monthPaint.setTypeface(Typeface.DEFAULT);
            weekPaint = new Paint();
            weekPaint.setColor(weekNormalColor);
            weekPaint.setAntiAlias(true);
            float weekTextSize = weekHeight * 0.6f;
            weekPaint.setTextSize(weekTextSize);
            weekPaint.setTypeface(Typeface.DEFAULT);
            datePaint = new Paint();
            datePaint.setColor(textColor);
            datePaint.setAntiAlias(true);

            float cellTextSize = cellHeight * 0.28f;
            datePaint.setTextSize(cellTextSize);
            datePaint.setTypeface(Typeface.DEFAULT);

            //上班所用画笔
            shangBanPaint = new Paint();
            shangBanPaint.setTextSize(cellTextSize / 2);
            shangBanPaint.setColor(MyApplication.Companion.getInstance().getResources().getColor(R.color.main_blue));
            //加班所用画笔
            jiaBanPaint = new Paint();
            jiaBanPaint.setTextSize(cellTextSize / 2);
            jiaBanPaint.setColor(MyApplication.Companion.getInstance().getResources().getColor(R.color.gallery_red));

            bottomValuePaint = new Paint();
            bottomValuePaint.setTextSize(cellTextSize / 1.2f);
            bottomValuePaint.setAntiAlias(true);
            bottomValuePaint.setColor(MyApplication.Companion.getInstance().getResources().getColor(R.color.gray_B3));
            boxPath = new Path();
            // boxPath.addRect(0, 0, width, height, Direction.CW);
            // boxPath.moveTo(0, monthHeight);
            boxPath.rLineTo(width, 0);
            boxPath.moveTo(0, monthHeight + weekHeight);
            boxPath.rLineTo(width, 0);
            for (int i = 1; i < 6; i++) {
                boxPath.moveTo(0, monthHeight + weekHeight + i * cellHeight);
                boxPath.rLineTo(width, 0);
                boxPath.moveTo(i * cellWidth, monthHeight);
                boxPath.rLineTo(0, height - monthHeight);
            }
            boxPath.moveTo(6 * cellWidth, monthHeight);
            boxPath.rLineTo(0, height - monthHeight);
            // preMonthBtnPath = new Path();
            // int btnHeight = (int) (monthHeight * 0.6f);
            // preMonthBtnPath.moveTo(monthChangeWidth / 2f, monthHeight / 2f);
            // preMonthBtnPath.rLineTo(btnHeight / 2f, -btnHeight / 2f);
            // preMonthBtnPath.rLineTo(0, btnHeight);
            // preMonthBtnPath.close();
            // nextMonthBtnPath = new Path();
            // nextMonthBtnPath.moveTo(width - monthChangeWidth / 2f,
            // monthHeight / 2f);
            // nextMonthBtnPath.rLineTo(-btnHeight / 2f, -btnHeight / 2f);
            // nextMonthBtnPath.rLineTo(0, btnHeight);
            // nextMonthBtnPath.close();
            monthChangeBtnPaint = new Paint();
            monthChangeBtnPaint.setAntiAlias(true);
            monthChangeBtnPaint.setStyle(Paint.Style.FILL_AND_STROKE);
            monthChangeBtnPaint.setColor(btnColor);
            cellBgPaint = new Paint();
            cellBgPaint.setAntiAlias(true);
            cellBgPaint.setStyle(Paint.Style.FILL);
            cellBgPaint.setColor(cellSelectedColor);

            startTimePaint = new Paint();
            startTimePaint.setAntiAlias(true);
            startTimePaint.setStyle(Paint.Style.FILL);
            startTimePaint.setColor(Color.parseColor("#e5e5e5"));

            endTimePaint = new Paint();
            endTimePaint.setAntiAlias(true);
            endTimePaint.setStyle(Paint.Style.FILL);
            endTimePaint.setColor(0x806CBC3D);
        }
    }
}
